package com.ruibang.glass.equipment.service.impl.device;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.nacos.common.utils.CollectionUtils;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mysql.jdbc.StringUtils;
import com.ruibang.glass.equipment.constant.Constants;
import com.ruibang.glass.equipment.constant.EquipmentErrorCode;
import com.ruibang.glass.equipment.domain.req.device.DeviceAllPageReq;
import com.ruibang.glass.equipment.entity.device.InstrumentRegister;
import com.ruibang.glass.equipment.entity.device.ScrapReport;
import com.ruibang.glass.equipment.mapper.device.InstrumentRegisterMapper;
import com.ruibang.glass.equipment.mapper.device.ScrapReportMapper;
import com.ruibang.glass.equipment.service.InstrumentRegisterService;
import com.teaming.cloud.framework2.common.exception.ServiceException;
import com.teaming.cloud.framework2.common.model.ResultBody;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 测量体系/仪表台账 务类
 * </p>
 *
 * @author mameng
 * @since 2024-03-20
 */
@Slf4j
@Service
public class InstrumentRegisterServiceImpl extends ServiceImpl<InstrumentRegisterMapper, InstrumentRegister> implements InstrumentRegisterService {

    @Autowired
    private ScrapReportMapper scrapReportMapper;

    /**
     * 测量体系/仪表台账 列表查询
     * @param deviceAllPageRea
     * @return
     */
    @Override
    public IPage<InstrumentRegister> queryPage(DeviceAllPageReq deviceAllPageRea) {
        return baseMapper.getCheckList(new Page<>(deviceAllPageRea.getPageNo(), deviceAllPageRea.getPageSize()), deviceAllPageRea);
    }

    /**
     * 跟新新增
     * @param accidentRegister
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultBody updateOrAddById(InstrumentRegister accidentRegister) {
        if (CollectionUtils.isNotEmpty(accidentRegister.getIds())) {
            List<InstrumentRegister> instrumentRegisters = baseMapper.selectBatchIds(accidentRegister.getIds());
            for (InstrumentRegister instrumentRegister : instrumentRegisters) {
                instrumentRegister.setStatus(accidentRegister.getStatus());
                baseMapper.updateById(instrumentRegister);
            }
            return ResultBody.success();
        }
        if (StringUtils.isNullOrEmpty(accidentRegister.getId())) {
            baseMapper.insert(accidentRegister);
            return ResultBody.success();
        }
        baseMapper.updateById(accidentRegister);
        return ResultBody.success();
    }

    /**
     * 新增报废报表
     * @param accidentRegister
     * @return
     */
    @Override
    public void addBfBb(InstrumentRegister accidentRegister) {
        List<InstrumentRegister> instrumentRegisters = baseMapper.selectBatchIds(accidentRegister.getIds());
        for (InstrumentRegister instrumentRegister : instrumentRegisters) {
            ScrapReport scrapReport = new ScrapReport();
            scrapReport.setEquipmentName(instrumentRegister.getName());
            scrapReport.setEquipmentNumber(instrumentRegister.getNumber());
            scrapReport.setUseDate(LocalDateTime.now());
            scrapReportMapper.insert(scrapReport);
        }
    }

    /**
     * 隐患台账导出
     * @param machiningReq
     * @param response
     */

    @Override
    public void export(DeviceAllPageReq machiningReq, HttpServletResponse response) {
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + "隐患台账" + ".xlsx");
        //获取导出数据
        IPage<InstrumentRegister> checkList = baseMapper.getCheckList(new Page<>(0L, 2000L), machiningReq);
        List<InstrumentRegister> list = checkList.getRecords();
        try {
            EasyExcel.write(response.getOutputStream(), InstrumentRegister.class).excelType(ExcelTypeEnum.XLSX).sheet("隐患台账").doWrite(list);
        } catch (IOException e) {
            throw new ServiceException(EquipmentErrorCode.EXPORT_FILE_IS_FAILED.getCode(), EquipmentErrorCode.EXPORT_FILE_IS_FAILED.getMsg());
        }
    }

    /**
     * 安周执行
     */
    @Override
    public void updateStatusByWeekTime() {
        List<String> statusList = new ArrayList<>();
        statusList.add("1");
        statusList.add("2");
        List<InstrumentRegister> instrumentRegisters = baseMapper.selectList(Wrappers.<InstrumentRegister>lambdaQuery().in(InstrumentRegister::getStatus, statusList).eq(InstrumentRegister::getUnit, Constants.POINT_WEEK));
        for (InstrumentRegister instrumentRegister : instrumentRegisters) {
            Date date = getDate(instrumentRegister.getCalibrationDate(), instrumentRegister.getCalibrationPeriod() * 7);
            Date dateNow = getDateNow(new Date());
            if (date.before(dateNow)) {
                instrumentRegister.setColorStatus(Constants.ZERO_STR);
                instrumentRegister.setStatus(Constants.FOUR_STR);
            } else {
                Integer dayCount = instrumentRegister.getCalibrationPeriod() * 7;
                if (dayCount > 20) {
                    Integer dayRe = dayCount - 20;
                    Date midDate = getDate(instrumentRegister.getCalibrationDate(), dayRe);
                    if (dateNow.compareTo(midDate) == Constants.ZERO_INT) {
                        instrumentRegister.setColorStatus(Constants.ONE_STR);
                    }
                } else {
                    Date midDate = getDate(instrumentRegister.getCalibrationDate(), dayCount);
                    if (dateNow.compareTo(midDate) == Constants.ZERO_INT) {
                        instrumentRegister.setColorStatus(Constants.ONE_STR);
                    }
                }
            }
            baseMapper.updateById(instrumentRegister);
        }

    }
    /**
     * 安月执行
     */
    @Override
    public void updateStatusByMonthTime() {
        List<String> statusList = new ArrayList<>();
        statusList.add("1");
        statusList.add("2");
        List<InstrumentRegister> instrumentRegisters = baseMapper.selectList(Wrappers.<InstrumentRegister>lambdaQuery().in(InstrumentRegister::getStatus, statusList).eq(InstrumentRegister::getUnit, Constants.POINT_WEEK));
        for (InstrumentRegister instrumentRegister : instrumentRegisters) {
            Date date = getDate(instrumentRegister.getCalibrationDate(), instrumentRegister.getCalibrationPeriod() * 30);
            Date dateNow = getDateNow(new Date());
            if (date.before(dateNow)) {
                instrumentRegister.setColorStatus(Constants.ZERO_STR);
                instrumentRegister.setStatus(Constants.FOUR_STR);
            } else {
                Integer dayCount = instrumentRegister.getCalibrationPeriod() * 30;
                if (dayCount > 20) {
                    Integer dayRe = dayCount - 20;
                    Date midDate = getDate(instrumentRegister.getCalibrationDate(), dayRe);
                    if (dateNow.compareTo(midDate) == Constants.ZERO_INT) {
                        instrumentRegister.setColorStatus(Constants.ONE_STR);
                    }
                } else {
                    Date midDate = getDate(instrumentRegister.getCalibrationDate(), dayCount);
                    if (dateNow.compareTo(midDate) == Constants.ZERO_INT) {
                        instrumentRegister.setColorStatus(Constants.ONE_STR);
                    }
                }
            }
            baseMapper.updateById(instrumentRegister);
        }

    }
    /**
     * 安年执行
     */
    @Override
    public void updateStatusByYearTime() {
        List<String> statusList = new ArrayList<>();
        statusList.add("1");
        statusList.add("2");
        List<InstrumentRegister> instrumentRegisters = baseMapper.selectList(Wrappers.<InstrumentRegister>lambdaQuery().in(InstrumentRegister::getStatus, statusList).eq(InstrumentRegister::getUnit, Constants.POINT_WEEK));
        for (InstrumentRegister instrumentRegister : instrumentRegisters) {
            Date date = getDate(instrumentRegister.getCalibrationDate(), instrumentRegister.getCalibrationPeriod() * 30);
            Date dateNow = getDateNow(new Date());
            if (date.before(dateNow)) {
                instrumentRegister.setColorStatus(Constants.ZERO_STR);
                instrumentRegister.setStatus(Constants.FOUR_STR);
            } else {
                Integer dayCount = instrumentRegister.getCalibrationPeriod() * 30;
                if (dayCount > 20) {
                    Integer dayRe = dayCount - 20;
                    Date midDate = getDate(instrumentRegister.getCalibrationDate(), dayRe);
                    if (dateNow.compareTo(midDate) == Constants.ZERO_INT) {
                        instrumentRegister.setColorStatus(Constants.ONE_STR);
                    }
                } else {
                    Date midDate = getDate(instrumentRegister.getCalibrationDate(), dayCount);
                    if (dateNow.compareTo(midDate) == Constants.ZERO_INT) {
                        instrumentRegister.setColorStatus(Constants.ONE_STR);
                    }
                }
            }
            baseMapper.updateById(instrumentRegister);
        }

    }

    /**
     * 按天执行
     */
    @Override
    public void updateStatusByDayTime() {
        List<String> statusList = new ArrayList<>();
        statusList.add("1");
        statusList.add("2");
        List<InstrumentRegister> instrumentRegisters = baseMapper.selectList(Wrappers.<InstrumentRegister>lambdaQuery().in(InstrumentRegister::getStatus, statusList).eq(InstrumentRegister::getUnit, Constants.POINT_DAY));
        for (InstrumentRegister instrumentRegister : instrumentRegisters) {
            Date date = getDate(instrumentRegister.getCalibrationDate(), instrumentRegister.getCalibrationPeriod());
            Date dateNow = getDateNow(new Date());
            if (date.before(dateNow)) {
                instrumentRegister.setColorStatus(Constants.ZERO_STR);
                instrumentRegister.setStatus(Constants.FOUR_STR);
            } else {
                Integer dayCount = instrumentRegister.getCalibrationPeriod();
                if (dayCount > 20) {
                    Integer dayRe = dayCount - 20;
                    Date midDate = getDate(instrumentRegister.getCalibrationDate(), dayRe);
                    if (dateNow.compareTo(midDate) == Constants.ZERO_INT) {
                        instrumentRegister.setColorStatus(Constants.ONE_STR);
                    }
                } else {
                    instrumentRegister.setColorStatus(Constants.ONE_STR);
                }
            }
            baseMapper.updateById(instrumentRegister);
        }

    }

    public Date getDate(Date date, Integer day) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        // 将日期增加一天，以获取明天的日期
        calendar.add(Calendar.DAY_OF_MONTH, day);
        // 清除时间部分，只保留日期
        calendar.set(Calendar.HOUR_OF_DAY, Constants.ZERO_INT);
        calendar.set(Calendar.MINUTE, Constants.ZERO_INT);
        calendar.set(Calendar.SECOND, Constants.ZERO_INT);
        calendar.set(Calendar.MILLISECOND, Constants.ZERO_INT);
        // 创建一个只包含日期部分的Date对象
        return calendar.getTime();
    }


    public Date getDateNow(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        // 清除时间部分，只保留日期
        calendar.set(Calendar.HOUR_OF_DAY, Constants.ZERO_INT);
        calendar.set(Calendar.MINUTE, Constants.ZERO_INT);
        calendar.set(Calendar.SECOND, Constants.ZERO_INT);
        calendar.set(Calendar.MILLISECOND, Constants.ZERO_INT);
        // 创建一个只包含日期部分的Date对象

        return calendar.getTime();
    }


}
